# code:utf8
import logging
from datetime import datetime
from zc_core.model.items import *
from zc_core.util.common import parse_number, parse_time
from zc_core.util.encrypt_util import md5
from pyquery import PyQuery
from liaoning.matcher import match_cat_id
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')


# 解析首页catalog列表
def parse_catalog(response):
    jpy = PyQuery(response.text)
    nav_list = jpy('ul#js_climit_li li.shopCatalogItem')

    cats = list()
    for nav1_li in nav_list.items():
        # 一级分类
        cat1_a = nav1_li('div.category-info h3.category-name > a')
        cat1_href = cat1_a.attr('href').strip()
        cat1_id = match_cat_id(cat1_href)
        cat1_name = cat1_a.text().strip()
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)
        # 二级分类
        html_text = nav1_li('textarea').html().replace('&amp;', '&')
        jpy_nav2 = PyQuery(html_text)
        cat2_dls = jpy_nav2('div.area-bg > div:eq(1) dl')
        for cat2_dl in cat2_dls.items():
            cat2_a = cat2_dl('dt.channel-items a.channel-items-link:eq(0)')
            cat2_href = cat2_a.attr('href').strip()
            cat2_id = match_cat_id(cat2_href)
            cat2_name = cat2_a.text().strip()
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

            # 三级分类
            cat3_links = cat2_dl('dd.channel-item a.channel-item-link')
            for cat3_link in cat3_links.items():
                # 三级分类
                cat3_href = cat3_link.attr('href').strip()
                cat3_name = cat3_link.text().strip()
                cat3_id = match_cat_id(cat3_href)
                cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = str(cat_id)
    cat['catalogName'] = cat_name
    cat['parentId'] = str(parent_id)
    cat['level'] = level
    if cat['level'] == 3:
        # 1、是
        cat['leafFlag'] = 1
    else:
        # 2、否
        cat['leafFlag'] = 2
    cat['linkable'] = 1

    return cat


# 解析order列表页数
def parse_sku_pages(response):
    jpy = PyQuery(response.text)
    next_page = jpy('a.pn-next')
    if next_page:
        prev = next_page.prev('a')
        if prev:
            return int(prev.eq(0).text())
    else:
        rows = jpy('div#list-panel div.item')
        if rows and len(rows):
            return 1

    return 0


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    divs = jpy('div#list-panel div.item')
    sku_list = list()
    if divs:
        for div in divs.items():
            sku = Sku()
            sku['skuId'] = str(div('input#productId').attr('value'))
            sku['supplierSkuId'] = str(div('input#skuId').attr('value'))
            sku['catalog3Id'] = meta.get('catalog3Id')
            sale_count = div('span.vol span').text()
            if sale_count:
                sku['soldCount'] = parse_number(sale_count.replace('笔', ''), 0)
            else:
                sku['soldCount'] = 0
            sku_list.append(sku)

    return sku_list


# 解析ItemData
def parse_item_data(response):
    meta = response.meta

    result = ItemData()
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    catalog3_id = meta.get('catalog3Id')
    meta_sp_sku_id = meta.get('supplierSkuId', '')
    sold_count = meta.get('soldCount', 0)

    jpy = PyQuery(response.text)
    brand_model = jpy('div.base-info ul.list li span:contains("型　　号：") + span')
    on_sale_time = jpy('div.base-info ul.list li span:contains("上架时间：") + span')
    gallery = jpy('div#gallery img')
    sp_id = jpy('input#marketId').attr('value')
    sp_name = jpy('input#marketName').attr('value')
    sp_sku_id = jpy('input#sku').attr('value')
    sale_price = parse_number(jpy('input#refPriceHidden').attr('value'))
    origin_price = parse_number(jpy('span#market-price').text())
    # 下架
    if sale_price <= 0:
        return None
    # 原价容错
    if origin_price <= 0 < sale_price:
        origin_price = sale_price

    # -------------------------------------------------
    # 批次编号
    result['batchNo'] = batch_no
    # 平台商品ID（用于业务系统）
    result['skuId'] = str(sku_id)
    # 平台商品名称（标题）
    result['skuName'] = jpy('input#productRealName').attr('value')
    # 平台商品主图（主图地址）
    if gallery:
        result['skuImg'] = gallery.eq(0).attr('src')
    # 一级分类编号
    result['catalog1Id'] = ''
    # 一级分类名称
    result['catalog1Name'] = ''
    # 二级分类编号
    result['catalog2Id'] = ''
    # 二级分类名称
    result['catalog2Name'] = ''
    # 三级分类编号
    result['catalog3Id'] = catalog3_id
    # 三级分类名称
    result['catalog3Name'] = ''
    # 实际销售价格
    result['salePrice'] = sale_price
    # 商品原价（商城原价、市场价格）
    result['originPrice'] = origin_price
    # 累计销售量（记录‘已销售’或‘月销量’）
    result['soldCount'] = sold_count
    # 品牌
    brand = jpy('input#productBrandName').attr('value')
    if brand:
        result['brandId'] = md5(brand.strip())
        result['brandName'] = brand.strip()
    # 供应商
    result['supplierId'] = sp_id
    result['supplierName'] = sp_name
    # 供应商商品编码(包含后缀)
    if not sp_sku_id:
        sp_sku_id = meta_sp_sku_id
    if sp_sku_id:
        result['supplierSkuId'] = sp_sku_id
        plat_code = None
        if sp_id == '15037719' or '得力' in sp_name:
            plat_code = 'deli'
        result['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
    # 供应商商品链接
    result['supplierSkuLink'] = jpy('span#label').parent('a').attr('href')
    # 品牌型号
    if brand_model and brand_model.text() != '-':
        result['brandModel'] = brand_model.text()
    # 上架时间
    if on_sale_time and on_sale_time.text().strip():
        result['onSaleTime'] = parse_time(on_sale_time.text().strip(), fmt='%Y年%m月%d日 %H:%M:%S')
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return result
